package cn.dogeye.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
@Data
@Component
@ConfigurationProperties(prefix = "jwt.config")
public final class JwtUtil {
    /*过期时间 单位分钟*/
    private int expire;
    private String salt;
    private String header;
    private String aaa;

    public String createToken(Claims claims){
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,expire);
        claims.setExpiration(calendar.getTime())// 设置过期时间
                .setIssuedAt(new Date());
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512,salt)
                .compact();
    }

    // 解析jwt
    public Claims getClaimByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(salt)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            throw e;
        }
    }
}
